//
//  CitiesViewController.m
//  Mtime
//
//  Created by Mac on 15/7/31.
//  Copyright (c) 2015年 wxk. All rights reserved.
//

#import "CitiesViewController.h"

@interface CitiesViewController ()
{

    IBOutlet UICollectionView *citiesCV;

    IBOutlet UITextField *textField;
    
    NSMutableDictionary *_citiesDic;//城市数据
    
    NSArray *_fileDataList;
    
    
    NSArray *hotCitiesArray;
    NSArray *lateCitiesArray;
/*
 *@{key : A/B/C
    value : @[DIC  DIC  DIC ../model  model  model..]}
 
 */
}
@end

@implementation CitiesViewController

//4.实现block的调用方法
- (void)addBlock:(citiesBlock)block{

    //给block赋值
    _block = block;

}

- (id)init {

    if (self = [super init]) {
        
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"home_top_movie_background_cover"]];
    }

    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    textField.delegate = self;
    
    [self loadData];//加载数据
    
    [self loadCollectionView];//加载视图
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChange:) name:UITextFieldTextDidChangeNotification object:nil];
    
}

- (void)textFieldChange:(NSNotification *)noti {

    UITextField *textF = (UITextField *)noti.object;
    
    //1.获得输入框的输入内容
    NSString *str = textF.text;
    
    //2.创建谓词
    NSString *p = [NSString stringWithFormat:@"self like [c] '*%@*'",str];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:p];
    
    //3.过滤数据
    if (![str isEqualToString:@""]) {
    
        _fileDataList = [_fileDataList filteredArrayUsingPredicate:predicate];
    }else {
        
        _fileDataList = @[@"热门城市",@"最近访问的城市",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z"];
    }
    
    //4.刷新数据
    [citiesCV reloadData];
    
}

- (void)loadData {

    _citiesDic = [[NSMutableDictionary alloc] init];
    
    //1.获取本地json文件的路径
    NSString *pathfile = [[NSBundle mainBundle] pathForResource:@"cities" ofType:@"json"];
    
    //2.将本地文件转换成data形式
    NSData *data = [NSData dataWithContentsOfFile:pathfile];
    
    //3.数据解析
    NSDictionary *citiesDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    
    NSDictionary *infor = [citiesDic objectForKey:@"infor"];
    NSArray *listItems = [infor objectForKey:@"listItems"];
    
    //数据处理
    for (NSDictionary *dic in listItems) {
    
        NSMutableArray *oldArray = [_citiesDic objectForKey:[dic objectForKey:@"charindex"]];
        
        if (!oldArray) {
            
            NSMutableArray *newArray = [[NSMutableArray alloc] init];
            
            [newArray addObject:dic];
            
            [_citiesDic setValue:newArray forKey:[dic objectForKey:@"charindex"]];
            
        }else {
        
            [oldArray addObject:dic];
            
        }
    }
    
    hotCitiesArray = @[@"北京",@"上海",@"章丘",@"长清",@"港沟"];
    lateCitiesArray = @[@"12马路",@"老屯",@"精益微博啊",@"阿萨德发",@"德玛西亚"];

    [_citiesDic setValue:hotCitiesArray forKey:@"热门城市"];
    [_citiesDic setValue:hotCitiesArray forKey:@"最近访问的城市"];
    
    _fileDataList = @[@"热门城市",@"最近访问的城市",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z"];
    
    
}

- (void)loadCollectionView {

    //1.设置flow layout：作用；设置单元格的尺寸／间距／翻转方向
    
    //2.初始化collectionview
//    UICollectionView *cv = [[UICollectionView alloc] initWithFrame:<#(CGRect)#> collectionViewLayout:<#(UICollectionViewLayout *)#>]
    citiesCV.backgroundColor = [UIColor clearColor];
    
    //3.设置代理
    citiesCV.dataSource = self;
    citiesCV.delegate = self;
    
    //4.注册单元格
    [citiesCV registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    //注册头视图
    /*
     - (void)registerClass:(Class)头视图的类名 forSupplementaryViewOfKind:(NSString *)视图类型｛头视图／尾视图｝ withReuseIdentifier:(NSString *)复用时的唯一标志符;
     */
    [citiesCV registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];

    
    
    
}

#pragma mark UICollectionViewDataSource
//返回组数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

    return _fileDataList.count;
}
//返回每组的单元格数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    NSString *key = _fileDataList[section];
    
    NSArray *arr = [_citiesDic objectForKey:key];
    
    return arr.count;

}
//返回单元格！！！！注意注册单元格
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    UILabel *label = [[UILabel alloc] initWithFrame:cell.contentView.bounds];
    label.backgroundColor = [UIColor cyanColor];
    label.textColor = [UIColor whiteColor];
    label.layer.cornerRadius = 15;
    label.layer.borderColor = [[UIColor purpleColor] CGColor];
    label.layer.borderWidth = 2;
    label.clipsToBounds = YES;
    label.layer.shadowColor = [[UIColor yellowColor] CGColor];
    
    NSString *key = _fileDataList[indexPath.section];
    
    NSArray *arr = [_citiesDic objectForKey:key];
    
    id class = arr[indexPath.item];

    if ([class isKindOfClass:[NSString class]]) {
        
        label.text = class;
    }else {
    
        label.text = [class objectForKey:@"name"];
    }
    
    
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:20];
    [cell.contentView addSubview:label];
    
    return cell;
    
}

//返回头／尾视图的方法！！！！注意注册头／尾视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {

    //判断返回视图的类型
    if (kind == UICollectionElementKindSectionHeader) {
    
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 44)];
        label.text = _fileDataList[indexPath.section];
        label.font = [UIFont systemFontOfSize:20];
        label.textColor = [UIColor whiteColor];
        label.backgroundColor = [UIColor grayColor];
        [header addSubview:label];
        
        return header;
    }

    return nil;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    NSString *str;
    NSString *key = _fileDataList[indexPath.section];
    
    NSArray *arr = [_citiesDic objectForKey:key];
    
    id class = arr[indexPath.item];
    
    if ([class isKindOfClass:[NSString class]]) {
        
        str = class;
    }else {
        str = [class objectForKey:@"name"];
    }
    
    //5.给block传值
    _block(str);

    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
